#include <stdio.h>
#include <linux/input.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <pthread.h>
#include <string.h>
#include <getopt.h>

void print_usage(const char *program_name) {
    printf("用法: %s [选项]\n", program_name);
    printf("选项:\n");
    printf("  -d <设备号>    指定输入设备 (例如: -d 0 表示 /dev/input/event0)\n");
    printf("  -h            显示此帮助信息\n");
    printf("\n示例:\n");
    printf("  %s -d 2       监听 /dev/input/event2\n", program_name);
    printf("  %s -d 0       监听 /dev/input/event0\n", program_name);
}

int main(int argc, char **argv)
{
	int ts_x = 0;
    int ts_y = 0;
    int event_fd = -1;
    struct input_event event_t;
    char device_path[256] = "/dev/input/event2"; // 默认设备
    int opt;
    
    // 解析命令行参数
    while ((opt = getopt(argc, argv, "d:h")) != -1) {
        switch (opt) {
            case 'd':
                if (optarg) {
                    snprintf(device_path, sizeof(device_path), "/dev/input/event%s", optarg);
                }
                break;
            case 'h':
                print_usage(argv[0]);
                return 0;
            default:
                print_usage(argv[0]);
                return 1;
        }
    }

    event_fd = open(device_path, O_RDONLY);
    if(-1 == event_fd){
        printf("打开 %s 失败!\n", device_path);
        return -1;
    }
    printf("成功打开 %s!\n", device_path);

    while(1){
        if(read(event_fd ,&event_t ,sizeof(event_t))){
            switch(event_t.type){
                case EV_SYN:
                    break ;
                case EV_ABS:
                    if(event_t.code == ABS_MT_POSITION_X){
                        ts_x = event_t.value ;
                        printf("ts_x : %d\n",ts_x);
                    };
                    if(event_t.code == ABS_MT_POSITION_Y){
                        ts_y = event_t.value ;
                        printf("ts_y : %d\n",ts_y);
                    };
                    break ;
				case EV_KEY:
					if(event_t.value==0 || event_t.value==1)
						printf("key %d %s\n", event_t.code, (event_t.value) ? "Pressed" : "Released");
                    break ;
                default:
                    break ;
            }
        }
    usleep(10000);
    }
    close(event_fd);

    return 0 ;
}